package com.eliza.base.views.learn.layouts.basic

import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.TargetedFlingBehavior
import androidx.compose.foundation.gestures.snapping.SnapFlingBehavior
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PageSize
import androidx.compose.foundation.pager.PagerDefaults
import androidx.compose.foundation.pager.PagerSnapDistance
import androidx.compose.foundation.pager.VerticalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.util.lerp
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.eliza.base.R
import kotlinx.coroutines.launch
import kotlin.math.absoluteValue

//分页器

@Preview
@Composable
private fun asas() {
    PagerX.Show(navController = rememberNavController())

}

object PagerX {
    @Composable
    fun Show(navController: NavController) {
        Column {
            var count by remember {
                mutableIntStateOf(0)
            }
            Button(onClick = { count = (count + 1) % 4 }) {
                Text(text = "ModifiersX $count")
            }
            when (count) {
                0 -> HorizontalPagerX()
                1 -> VerticalPagerX()
                2 -> HorizontalPagerAnimationX()
                3 -> PageSizeX()
            }
        }
    }


    var imgx: @Composable () -> Unit = {
        Image(
            painter = painterResource(id = R.drawable.ic_launcher),
            contentDescription = null,
            contentScale = ContentScale.FillWidth,
            modifier = Modifier
                .fillMaxWidth()
        )
    }

    /*
    *
    * 延迟创建
    HorizontalPager 和 VerticalPager 中的页面会根据需要进行延迟组合和布局。
    * 当用户滚动页面时，该可组合项会移除不再需要的所有页面。
    * */
    @Composable
    private fun HorizontalPagerX() {
        // Display 10 items
        val pagerState = rememberPagerState(pageCount = {
            10
        })
        HorizontalPager(state = pagerState) { page ->
            // Our page content
            imgx()
        }
    }

    @Composable
    private fun VerticalPagerX() {
        // Display 10 items
        val pagerState = rememberPagerState(pageCount = {
            10
        })
        Row {
            LaunchedEffect(pagerState) {
                // Collect from the a snapshotFlow reading the currentPage
                snapshotFlow { pagerState.currentPage }.collect { page ->
                    // Do something with each page change, for example:
                    // viewModel.sendPageSelectedEvent(page)
                    Log.d("Page change", "Page changed to $page")
                }
            }
            VerticalPager(state = pagerState, modifier = Modifier.weight(1f)) { page ->
                // Our page content
                imgx()
                Text(
                    text = "Page: $page",
                    color = Color.Yellow,
                    modifier = Modifier.fillMaxWidth()
                )
            }
            // scroll to page
            val coroutineScope = rememberCoroutineScope()
            Button(onClick = {
                coroutineScope.launch {
                    //pagerState.scrollToPage(5) // 跳转
                    pagerState.animateScrollToPage(5)// 动画
                }
            }, modifier = Modifier.align(Alignment.CenterVertically)) {
                Text("Jump to Page 5")
            }

            //添加页面指示器
            Column(
                Modifier
                    .weight(1f)
                    .wrapContentHeight()
                    .fillMaxWidth()
                    .align(Alignment.Top)
                    .padding(bottom = 8.dp),
                verticalArrangement = Arrangement.Top
            ) {
                repeat(pagerState.pageCount) { iteration ->
                    val color =
                        if (pagerState.currentPage == iteration) Color.DarkGray else Color.LightGray
                    Box(
                        modifier = Modifier
                            .padding(5.dp)
                            .background(color)
                            .size(50.dp)
                    ) {
                        Text(
                            text = "Page ${pagerState.currentPage} ${pagerState.pageCount}",
                            color = Color.Blue,
                            fontSize = 10.sp,
                        )
                    }
                }
            }
        }
    }

    /*
    *
    * 接收有关页面状态更改的通知
        PagerState 有三个属性包含页面相关信息：currentPage、settledPage 和 targetPage。
        currentPage：最接近贴靠位置的页面。默认情况下，贴靠位置位于布局的开头。
        settledPage：未运行动画或滚动时的页码。这与 currentPage 属性不同，因为当页面足够接近贴靠位置时，currentPage 会立即更新，但 settledPage 会保持不变，直到所有动画都运行完毕为止。
        targetPage：建议的滚动移动停止位置。
    * */
//    将项滚动效果应用于内容
//    一个常见的用例是使用滚动位置将效果应用于分页器项。如需了解某个页面与当前所选页面之间的距离，
//    您可以使用 PagerState.currentPageOffsetFraction。
//    然后，您可以根据与所选页面的距离，对内容应用转换效果。
    @OptIn(ExperimentalFoundationApi::class)
    @Composable
    private fun HorizontalPagerAnimationX() {
        //一个常见的用例是使用滚动位置将效果应用于分页器项。如需了解某个页面与当前所选页面之间的距离，
        // 您可以使用 PagerState.currentPageOffsetFraction。然后，您可以根据与所选页面的距离，对内容应用转换效果。
        val pagerState = rememberPagerState(pageCount = {
            5
        })
        Column {
            HorizontalPager(
                state = pagerState,
            ) { page ->
                Card(
                    modifier = Modifier
                        .size(200.dp)
                        .graphicsLayer {
                            // Calculate the absolute offset for the current page from the
                            // scroll position. We use the absolute value which allows us to mirror
                            // any effects for both directions
                            val pageOffset = (
                                    //  了解某个页面与当前所选页面之间的距离，您可以使用 PagerState.currentPageOffsetFraction
                                    (pagerState.currentPage - page) + pagerState.currentPageOffsetFraction
                                    ).absoluteValue

                            // We animate the alpha, between 50% and 100%
                            alpha = lerp(
                                start = 0.5f,
                                stop = 1f,
                                fraction = 1f - pageOffset.coerceIn(0f, 1f)
                            )
                        }
                ) {
                    Text(text = "Card ${pagerState.currentPage}", color = Color.Yellow)
                    imgx()
                }
            }
            //添加页面指示器
            Row(
                Modifier
                    .wrapContentHeight()
                    .fillMaxWidth()
                    .padding(bottom = 8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                repeat(pagerState.pageCount) { iteration ->
                    val color =
                        if (pagerState.currentPage == iteration) Color.DarkGray else Color.LightGray
                    Box(
                        modifier = Modifier
                            .padding(5.dp)
                            .background(color)
                            .size(50.dp)
                    ) {
                        Text(
                            text = "Page ${pagerState.currentPage} ${pagerState.pageCount}",
                            color = Color.Blue,
                            fontSize = 10.sp,
                        )
                    }
                }
            }
        }
    }

    @Composable
    private fun PageSizeX() {
        val threePagesPerViewport = object : PageSize {
            override fun Density.calculateMainAxisPageSize(
                availableSpace: Int,
                pageSpacing: Int
            ): Int {
                return (availableSpace - 2 * pageSpacing) / 3
            }
        }
        val pagerState = rememberPagerState(pageCount = {
            4
        })
        val asd: @Composable (pv: PaddingValues) -> Unit = { pv ->
            HorizontalPager(
                state = pagerState,
                pageSize = threePagesPerViewport,
                //start 内边距可使页面向末尾对齐
                //将 start 和 end 的内边距设为相同的值，会使内容在水平方向上居中
                contentPadding = pv
            ) { page ->
                Card(
                    modifier = Modifier
                        .size(200.dp)
                        .graphicsLayer {
                            val pageOffset = (
                                    (pagerState.currentPage - page) + pagerState
                                        .currentPageOffsetFraction
                                    ).absoluteValue
                            // We animate the alpha, between 50% and 100%
                            alpha = lerp(
                                start = 0.5f,
                                stop = 1f,
                                fraction = 1f - pageOffset.coerceIn(0f, 1f)
                            )
                        }
                ) {
                    Text(text = "Card $pagerState", color = Color.Yellow)
                }
            }
        }
        Column {
            asd(PaddingValues(start = 60.dp, end = 5.dp))
            asd(PaddingValues(start = 60.dp, end = 30.dp))
            asd(PaddingValues(end = 30.dp))
            asd(PaddingValues(horizontal = 32.dp))
        }


    }

    @Composable
    private fun PagerSnapX() {
        val pagerState = rememberPagerState(pageCount = { 10 })
        /*
        * 可组合项指定了滚动手势如何与分页器配合使用。
        * 自定义和更改 pagerSnapDistance 或 flingBehaviour 等默认值。
        *
        * 贴靠距离
默认情况下，HorizontalPager 和 VerticalPager 用于设置快速滑动手势每次可以滚动至一页的页面数量上限。
* 如需更改此设置，请在 flingBehavior 上设置 pagerSnapDistance：
        * */
        val fling = PagerDefaults.flingBehavior(
            state = pagerState,
            pagerSnapDistance = PagerSnapDistance.atMost(10)
        )
        val asd: @Composable (flingBehavior: TargetedFlingBehavior) -> Unit = { flingBehavior ->
            HorizontalPager(
                state = pagerState,
                pageSize = PageSize.Fixed(200.dp),
                beyondViewportPageCount = 10,
                //start 内边距可使页面向末尾对齐
                //将 start 和 end 的内边距设为相同的值，会使内容在水平方向上居中
                flingBehavior = flingBehavior,
            ) { page ->
                Card(
                    modifier = Modifier
                        .size(200.dp)
                        .graphicsLayer {
                            val pageOffset = (
                                    (pagerState.currentPage - page) + pagerState
                                        .currentPageOffsetFraction
                                    ).absoluteValue
                            // We animate the alpha, between 50% and 100%
                            alpha = lerp(
                                start = 0.5f,
                                stop = 1f,
                                fraction = 1f - pageOffset.coerceIn(0f, 1f)
                            )
                        }
                ) {
                    Text(text = "Card $pagerState", color = Color.Yellow)
                }
            }
        }
        Column {
            asd(fling)
        }

    }

}